<?php

namespace app\storeapi\model\dealer;

use app\storeapi\model\User as UserModel;
use app\storeapi\model\Wxapp as WxappModel;
use app\common\model\dealer\Withdraw as WithdrawModel;
use app\common\library\wechat\WxPay;
use app\common\service\Order as OrderService;
use app\common\service\Message as MessageService;
use app\common\enum\dealer\withdraw\ApplyStatus as ApplyStatusEnum;
use app\common\enum\dealer\withdraw\PayType as PayTypeEnum;

/**
 * 分销商提现明细模型
 * Class Withdraw
 * @package app\store\model\dealer
 */
class Withdraw extends WithdrawModel
{
    /**
     * 获取器：申请时间
     * @param $value
     * @return false|string
     */
    public function getAuditTimeAttr($value)
    {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : 0;
    }

    /**
     * 获取器：打款方式
     * @param $value
     * @return mixed
     */
    public function getPayTypeAttr($value)
    {
        return ['text' => PayTypeEnum::data()[$value]['name'], 'value' => $value];
    }

    /**
     * 获取器：申请状态
     * @param $value
     * @return mixed
     */
    public function getApplyStatusAttr($value)
    {
        return ['text' => ApplyStatusEnum::data()[$value]['name'], 'value' => $value];
    }

    /**
     * 获取分销商提现列表
     * @param int $apply_status
     * @param int $page
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($data)
    {
        // 商品列表获取条件
        $param = array_merge([
            'apply_status' => 0,     // 审核状态
        ], $data);
        // 筛选条件
        $filter = [];
        $filter['withdraw.wxapp_id'] = $param['wxapp_id'];
        $data['apply_status'] > 0 && $filter['withdraw.apply_status'] = ['=',$data['apply_status']];
        $page = isset($param['page']) && is_numeric($param['page']) ? intval($param['page']) : 1;
        $limit = 15;
        $offset = ($page - 1) * $limit;
        // 构建查询规则
        $list = $this->alias('withdraw')
            ->join('dealer_user b', 'b.user_id = withdraw.user_id')
            ->join('user c', 'c.user_id = withdraw.user_id')
            ->field('withdraw.*, b.real_name,b.mobile,c.nickName')
            ->where($filter)
            ->limit($offset, $limit)
            ->order(['withdraw.create_time' => 'desc'])
            ->select();
        return $list;
    }

    /**
     * 分销商提现审核
     * @param $data
     * @return bool
     */
    public function submit($data)
    {
//
//        if($data['apply_status'] == ApplyStatusEnum::AUDIT_REJECT  && empty($data['reject_reason'])) {
//            $this->error = '请填写驳回原因';
//            return false;
//        }
        $this->transaction(function () use ($data) {
            // 更新申请记录
            $data['audit_time'] = time();
            $this->allowField(true)->save($data);
            // 提现驳回：解冻分销商资金
            if ($data['apply_status'] == ApplyStatusEnum::AUDIT_REJECT) {
                User::backFreezeMoney($this['user_id'], $this['money']);
            }
            // 发送消息通知
            MessageService::send('dealer.withdraw', [
                'withdraw' => $this,
                'user' => UserModel::detail($this['user_id']),
            ]);
        });
        return true;
    }

    /**
     * 分销商提现：微信支付企业付款
     * @return bool
     * @throws \app\common\exception\BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function wechatPay($param)
    {

        // 微信用户信息
        $user = $this['user']['user'];
        // 生成付款订单号
        $orderNO = OrderService::createOrderNo();
        // 付款描述
        $desc = '分销商提现付款';
        // 微信支付api：企业付款到零钱
        $wxConfig = WxappModel::getWxappInfo($param['wxapp_id']);
        $WxPay = new WxPay($wxConfig);
        // 请求付款api

        if ($WxPay->transfers($orderNO, $user['open_id'], $this['money'], $desc)) {
            // 确认已打款
            $this->money();
            return true;
        }
        return false;
    }


    /**
     * 确认已打款
     * @return bool
     */
    public function money()
    {
        $this->transaction(function () {
            // 更新申请状态
            $this->allowField(true)->save([
                'apply_status' => 40,
                'audit_time' => time(),
            ]);
            // 更新分销商累积提现佣金
            User::totalMoney($this['user_id'], $this['money']);
            // 记录分销商资金明细
            Capital::add([
                'user_id' => $this['user_id'],
                'flow_type' => 60,
                'money' => -$this['money'],
                'describe' => '申请提现',
            ]);
        });
        return true;
    }


}